package com.empi.storage.service.impl;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class FileServiceImpl {

    public static void main(String[] args) {
        try {
            String endPoint = "http://11.125.1.249";
            String ak = "6WNRCBYLMT5OLYHOYWNC";
            String sk = "QhSbEwDgGG1liQlEyCM5emC4AqflgzndutSbKMnD";
// 创建ObsClient实例
            ObsClient obsClient = new ObsClient(ak, sk, endPoint);
            //String str ="05367529/0000679d1398be9047c965d6c3aca9ae/575a3c3b51c1be71a9d44331426b4b45/";
            //System.out.println(str.substring(str.length()-1,str.length()));
          // String prefix ="05362252/";
            String prefix ="06/";
           //统计子文件个数
          // int count = count(obsClient,prefix);
          // System.out.println("共有"+count+"个子文件");
            folderSize(obsClient,prefix);
            // deleteObject(obsClient);
           // batchDeleteObject(obsClient);

           // listHosipital(obsClient);
           // listHosipitalChild(obsClient);
            //folderGroup(obsClient);
// 关闭obsClient
            obsClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }





    //查询当前文件夹有多少个子文件夹
    static int count(ObsClient obsClient,String prefix){
        long startTime = System.currentTimeMillis();
        System.out.println("开始统计文件夹下有多少个文件"+startTime);
        Integer count =0;
        ListObjectsRequest request = new ListObjectsRequest("obs-4678");
        request.setMaxKeys(1000);
        request.setPrefix(prefix);
     //   request.setDelimiter("/");
        ObjectListing result = null;
        do {
            result = obsClient.listObjects(request);
           List<String> list = result.getCommonPrefixes();
           request.setMarker(result.getNextMarker());
            count+=list.size();
        }while (result.isTruncated());
       long endTime = System.currentTimeMillis();
       System.out.println("统计文件夹下有"+count+"个子文件结束，共耗时"+(endTime-startTime)+"毫秒");
        return count;
    }

    static long folderSize(ObsClient obsClient,String prefix){
        long startTime = System.currentTimeMillis();
        System.out.println("开始统计文件夹大小"+startTime);
        Integer count =0;
        ListObjectsRequest request = new ListObjectsRequest("mic");
        request.setMaxKeys(1000);
        request.setPrefix(prefix);
       // request.setDelimiter("/");
        ObjectListing result = null;
        long size =0;
     //  ObjectMetadata metadata = obsClient.getObjectMetadata("mic",prefix);
     //   size = metadata.getContentLength();
        do {
            result = obsClient.listObjects(request);
           List<ObsObject> objectsList = result.getObjects();
           for (ObsObject obs : objectsList){
              size += obs.getMetadata().getContentLength();
           }
            request.setMarker(result.getNextMarker());
            count+=objectsList.size();
        }while (result.isTruncated());
        long endTime = System.currentTimeMillis();
        System.out.println("统计文件夹下有"+count+"个子文件结束，共耗时"+(endTime-startTime)+"毫秒");
        System.out.println("统计文件夹大小结束共"+size+"byte,"+size/1024/1024+"Mb，共耗时"+(endTime-startTime)+"毫秒");
        return count;
    }


    static void deleteObject(ObsClient obsClient){
        ListObjectsRequest request = new ListObjectsRequest("mic");
        request.setMaxKeys(100);
        // 设置文件夹分隔符"/"
       // request.setDelimiter("/");
        //request.setPrefix("/05");
        ObjectListing result;
        //request.setPrefix("05367529/0000679d1398be9047c965d6c3aca9ae/f974807f24597a42f3ca04f5e47cad5b/14c78c9eff040d44585b3249b8c17808/");
                  // 05367529/0000679d1398be9047c965d6c3aca9ae/12e63692f1800c87f110905f62d4a5b3/
        request.setPrefix("0533001/2021/06/17/1.2.840.113619.2.289.3.2831187968.683.1623776397.531/");
        result = obsClient.listObjects(request);
        List<ObsObject> objectList = result.getObjects();
        for(ObsObject object : objectList){
            System.out.println(object.getObjectKey());
            DeleteObjectResult objectResult =  obsClient.deleteObject("mic", object.getObjectKey());
            System.out.println(objectResult.getStatusCode()+"响应编码");
            System.out.println(objectResult);

        }
       List<String> folderList = result.getCommonPrefixes();
        for(String str : folderList){

        }

    }

    static void batchDeleteObject(ObsClient obsClient){

        ListObjectsRequest request = new ListObjectsRequest("mic");
        request.setMaxKeys(2);
        request.setPrefix("0000001/2023/2022/");
        request.setDelimiter("/");
        ObjectListing result = null;
        ObjectListing tempListResult = null;
        DeleteObjectsResult deleteResult = null;
        DeleteObjectsRequest delteRequest = new DeleteObjectsRequest("mic");
        // 设置为verbose模式 详细模式,返回所有请求结果，true 只返回错误结果
        delteRequest.setQuiet(false);
        do {
            List<KeyAndVersion> toDelete = new ArrayList<KeyAndVersion>();
            result = obsClient.listObjects(request);
            for(ObsObject obsObject : result.getObjects())
            {
                toDelete.add(new KeyAndVersion(obsObject.getObjectKey()));
                System.out.println("要删除的文件添加的key  "+obsObject.getObjectKey());
            }
            if(toDelete.size()>0){
                delteRequest.setKeyAndVersions(toDelete.toArray(new KeyAndVersion[toDelete.size()]));
                deleteResult = obsClient.deleteObjects(delteRequest);
            }
            for(String prefix : result.getCommonPrefixes())
            {
                deletelistObjectsByPrefix(obsClient,prefix);
            }

        }while (result.isTruncated());
//      获取删除成功的对象
        System.out.println(deleteResult.getDeletedObjectResults());
// 获取删除失败的对象
        System.out.println(deleteResult.getErrorResults());

    }
    static void listHosipital(ObsClient obsClient){
        ListObjectsRequest request = new ListObjectsRequest("obs-4678");
        request.setMaxKeys(10);
        // 设置文件夹分隔符"/"
        request.setDelimiter("/");
        //request.setPrefix("/05");
        ObjectListing result;
        do {
           result = obsClient.listObjects(request);
            List<String> hosipitalIdList =  result.getCommonPrefixes();
            String marker = result.getNextMarker();
            request.setMarker(marker);
            System.out.println("marker = " + marker);
            for (String str : hosipitalIdList){
                System.out.println("str = " + str);
            }
        }while (result.isTruncated());

    }

    static void listHosipitalChild(ObsClient obsClient){
        ListObjectsRequest request = new ListObjectsRequest("obs-4678");
        request.setMaxKeys(100);
        // 设置文件夹分隔符"/"
        request.setDelimiter("/");
        //request.setPrefix("/05");
        ObjectListing result;
            request.setPrefix("05361484/0000cbfcd472cf75d8b7980aff764ac3/fcb619ba72bb2c5a115ac8e4fdaf01f0/9bc1c46d790c30d5ba4a4ad3640b664c/");
            result = obsClient.listObjects(request);
            List<String> hosipitalIdList =  result.getCommonPrefixes();
            String marker = result.getNextMarker();
            request.setMarker(marker);
            System.out.println("marker = " + marker);
            for (String str : hosipitalIdList){
                System.out.println("str = " + str);
            }
        //}while (result.isTruncated());

    }

    //列举桶
    static void listBuckets(ObsClient obsClient){
        // 列举桶
        ListBucketsRequest request = new ListBucketsRequest();
        request.setQueryLocation(true);
        List<ObsBucket> buckets = obsClient.listBuckets(request);
        //遍历桶
        for(ObsBucket bucket : buckets)
        {
            System.out.println("BucketName:" + bucket.getBucketName());
            System.out.println("CreationDate:" + bucket.getCreationDate());
            System.out.println("Location:" + bucket.getLocation());
        }
    }

    public static void folderGroup(ObsClient obsClient) throws Exception{
        // 创建ObsClient实例

        ListObjectsRequest request = new ListObjectsRequest("obs-4678");
        request.setMaxKeys(10);
        // 设置文件夹分隔符"/"
        request.setDelimiter("/");
        ObjectListing result = obsClient.listObjects(request);
        System.out.println("Objects in the root directory:");

        for(ObsObject obsObject : result.getObjects())
        {
            System.out.println("\t" + obsObject.getObjectKey());
           // System.out.println("\t" + obsObject.getOwner());
        }
       // listObjectsByPrefix(obsClient, request, result);
// 关闭obsClient
        obsClient.close();
    }

    static void listObjectsByPrefix(ObsClient obsClient, ListObjectsRequest request, ObjectListing result) throws
            ObsException
    {
        for(String prefix : result.getCommonPrefixes())
        {
            System.out.println("Objects in folder [" + prefix + "]:");

                request.setPrefix(prefix);
                result = obsClient.listObjects(request);

            for(ObsObject obsObject : result.getObjects())
            {
                System.out.println("\t" + obsObject.getObjectKey());
                System.out.println("\t" + obsObject.getOwner());
            }
            listObjectsByPrefix(obsClient, request, result);
        }
    }

    static void deletelistObjectsByPrefix(ObsClient obsClient,String prefix) throws
            ObsException
    {
        ListObjectsRequest request = new ListObjectsRequest("mic");
        request.setMaxKeys(2);
        request.setPrefix(prefix);
        request.setDelimiter("/");
        ObjectListing result = null;
        ObjectListing tempListResult = null;
        DeleteObjectsResult deleteResult = null;
        DeleteObjectsRequest delteRequest = new DeleteObjectsRequest("mic");
        do {
            List<KeyAndVersion> toDelete = new ArrayList<KeyAndVersion>();
            result = obsClient.listObjects(request);
            for(ObsObject obsObject : result.getObjects())
            {
                toDelete.add(new KeyAndVersion(obsObject.getObjectKey()));
                System.out.println("要删除的文件添加的key  "+obsObject.getObjectKey());
            }
            if(toDelete.size()>0){
                delteRequest.setKeyAndVersions(toDelete.toArray(new KeyAndVersion[toDelete.size()]));
                deleteResult = obsClient.deleteObjects(delteRequest);
            }
            for(String str : result.getCommonPrefixes())
            {
                deletelistObjectsByPrefix(obsClient,str);
            }

        }while (result.isTruncated());

    }

}
